using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Domain.Entities.App;


namespace UniversalAdmin.Infrastructure.Data.Contexts;

public class AdminDbContext : DbContext
{
    public AdminDbContext(DbContextOptions<AdminDbContext> options) : base(options) { }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<Menu> Menus { get; set; }
    public DbSet<OperationLog> OperationLogs { get; set; }
    public DbSet<SystemConfig> SystemConfigs { get; set; }
    public DbSet<Domain.Entities.App.File> Files { get; set; }
    public DbSet<Article> Articles { get; set; }
    public DbSet<ArticleCategory> ArticleCategories { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // User-Role 多对多关系配置
        modelBuilder.Entity<User>()
            .HasMany(u => u.Roles)
            .WithMany(r => r.Users)
            .UsingEntity<Dictionary<string, object>>(
                "user_roles",
                j => j
                    .HasOne<Role>()
                    .WithMany()
                    .HasForeignKey("RoleId")
                    .HasPrincipalKey(nameof(Role.Id))
                    .OnDelete(DeleteBehavior.Cascade),
                j => j
                    .HasOne<User>()
                    .WithMany()
                    .HasForeignKey("UserId")
                    .HasPrincipalKey(nameof(User.Id))
                    .OnDelete(DeleteBehavior.Cascade),
                j =>
                {
                    j.HasKey("UserId", "RoleId");
                    j.Property<Guid>("UserId").HasColumnName("user_id");
                    j.Property<Guid>("RoleId").HasColumnName("role_id");
                });

        // Role-Menu 多对多关系配置
        modelBuilder.Entity<Role>()
            .HasMany(r => r.Menus)
            .WithMany(m => m.Roles)
            .UsingEntity<Dictionary<string, object>>(
                "role_menus",
                j => j
                    .HasOne<Menu>()
                    .WithMany()
                    .HasForeignKey("MenuId")
                    .HasPrincipalKey(nameof(Menu.Id))
                    .OnDelete(DeleteBehavior.Cascade),
                j => j
                    .HasOne<Role>()
                    .WithMany()
                    .HasForeignKey("RoleId")
                    .HasPrincipalKey(nameof(Role.Id))
                    .OnDelete(DeleteBehavior.Cascade),
                j =>
                {
                    j.HasKey("RoleId", "MenuId");
                    j.Property<Guid>("RoleId").HasColumnName("role_id");
                    j.Property<Guid>("MenuId").HasColumnName("menu_id");
                });
    }
}